<template>
  <j-modal
    :title="'选择'+name"
    :width="modalWidth"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    wrapClassName="j-depart-select-modal"
    switchFullscreen
    cancelText="关闭">
    <a-spin tip="Loading..." :spinning="false">
      <a-row :gutter="16">
        <a-col :span="16">
      <a-input-search style="margin-bottom: 1px" :placeholder="'请输入'+name+'名称按回车进行搜索'" @search="onSearch" />

        </a-col>
         <a-col :span="8">
           <div class="drawer-bootom-button">
        <a-dropdown :trigger="['click']" placement="topCenter">
          <a-menu slot="overlay">
            <a-menu-item v-if="multi" key="1" @click="switchCheckStrictly(1)">父子关联</a-menu-item>
            <a-menu-item v-if="multi" key="2" @click="switchCheckStrictly(2)">取消关联</a-menu-item>
            <a-menu-item v-if="multi" key="3" @click="checkALL">全部勾选</a-menu-item>
            <a-menu-item v-if="multi" key="4" @click="cancelCheckALL">取消全选</a-menu-item>
            <a-menu-item key="5" @click="expandAll">展开所有</a-menu-item>
            <a-menu-item key="6" @click="closeAll">合并所有</a-menu-item>
          </a-menu>
          <a-button>
            {{name}}树操作 <a-icon type="up" />
          </a-button>
        </a-dropdown>
      </div>
         </a-col>
      </a-row>
      <a-empty v-if="!treeData||treeData.length==0"/>
      <a-tree
        v-else
        checkable
        class="my-dept-select-tree"
        :treeData="treeData"
        :checkStrictly="checkStrictly"
        @check="onCheck"
        @select="onSelect"
        @expand="onExpand"
        :autoExpandParent="autoExpandParent"
        :expandedKeys="expandedKeys"
        :checkedKeys="checkedKeys">

        <template slot="title" slot-scope="{title}">
          <span v-if="title.indexOf(searchValue) > -1">
            {{title.substr(0, title.indexOf(searchValue))}}
            <span style="color: #f50">{{searchValue}}</span>
            {{title.substr(title.indexOf(searchValue) + searchValue.length)}}
          </span>
          <span v-else>{{title}}</span>
        </template>
      </a-tree>

    </a-spin>
  </j-modal>
</template>

<script>
 import { httpAction, getAction } from '@/api/manage'
  export default {
    name: 'JSelectDepartModal',
    props:['modalWidth','multi','rootOpened','departId','name','url','replaceFields','queryParam','needSelect','filterFirstDep','parentConfig'],
    data(){
      return {
        visible:false,
        confirmLoading:false,
        treeData:[],
        autoExpandParent:true,
        expandedKeys:[],
        dataList:[],
        checkedKeys:[],
        checkedRows:[],
        searchValue:"",
       expandedKeys:[],
       checkStrictly:true,
       checkStriccheckStrictlytly:false,
       allTreeKeys:[],
       expandAllKeys:[],
      }
    },
    mounted(){
      this.loadDepart();
    },
    watch:{
      departId(){
        this.initDepartComponent()
      },
      visible: {
        handler(val) {
          if (this.departId) {
            this.checkedKeys = this.departId.split(",");
            // console.log('this.departId', this.departId)
          } else {
            this.checkedKeys = [];
          }
         
        }
      },
      url(newVal ,oldVal){
          if(newVal != oldVal){
              // this.loadDepart();
          }
      },
    },
    methods:{
       //---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------
      expandAll () {
        this.expandedKeys = this.expandAllKeys
      },
      closeAll () {
        this.expandedKeys = []
      },
      checkALL () {
        this.checkStriccheckStrictlytly = false
        if(!this.multi){
          this.$message.warning("单选模式不支持全选")
          return
        }
        this.checkedKeys = this.allTreeKeys
      },
      cancelCheckALL () {
        //this.checkedKeys = this.defaultCheckedKeys
        this.checkedKeys = []
      },
      switchCheckStrictly (v) {
        
        if(v==1){
          this.checkStrictly = false
        }else if(v==2){
          this.checkStrictly = true
        }
      },
      getAllKeys(arr) {
        // console.log('node',node);+
          for(let node of arr){
              if(!node.disabled){
                this.allTreeKeys.push(node.key)
              }
              this.expandAllKeys.push(node.key)
              if (node.children && node.children.length > 0) {
                this.getAllKeys(node.children)
              }
          }
        
       
      },
      //---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------
      show(){
        this.visible=true
        this.checkedRows=[]
        this.checkedKeys=[]
        this.searchValue=''
      },
      loadDepart(){
          let queryParam = Object.assign({},this.queryParam)
         getAction(this.url, queryParam).then(res => {
            if (res.success) {
                this.allTreeKeys = [];
                let result = res.result.records || res.result 
                let arr = [...result]
                this.reWriterWithSlot(arr)
                this.treeData = arr
                this.initDepartComponent()
                
                this.getAllKeys(arr);
                if(this.rootOpened){
                  //全部展开
                  // this.initExpandedKeys(arr)
                   this.expandAll()
                }
                
            } else {
                this.$message.error(`获取${this.name}数据错误`);
            }
            });
      },
      
      initDepartComponent(){
        let names = ''
        if(this.departId){
          let currDepartId = this.departId
          
          for(let item of this.dataList){
            if(currDepartId.split(",").some(curr=>{return curr == item.key })){
              names+=","+item.title
            }
          }
          if(names){
            names = names.substring(1)
          }
        }
        this.$emit("initComp",names)
      },
      reWriterWithSlot(arr){
        for(let item of arr){
          item.children = !!item[this.replaceFields.children]?item[this.replaceFields.children]:[]
          item.title = item[this.replaceFields.title]
          item.key = item[this.replaceFields.key]
          item.value = item[this.replaceFields.value]
          if(this.filterFirstDep ){
            //部门树过滤A级部门
            item.disabled = true
            if(item.jgType && item.jgType.indexOf('A')>-1){
              item.disabled = false
            }
            item.selectable = !item.disabled
          }
          if(!item.key){
              item.key = item.id
              item.value = item.id
            }
            if(!item.label){
              item.label = item.title
            }
           item.scopedSlots={ title: 'title' }        

          if(item.children && item.children.length>0){
            this.reWriterWithSlot(item.children)
            let temp = Object.assign({},item)
            temp.children = {}
            this.dataList.push(temp)
          }else{
            this.dataList.push(item)
          }
        }
      },
      initExpandedKeys(arr){
        if(arr && arr.length>0){
          let keys = []
          for(let item of arr){
            if(item.children && item.children.length>0){
              keys.push(item.key)
            }
          }
          this.expandedKeys=[...keys]
        }else{
          this.expandedKeys=[]
        }
      },
      onCheck (checkedKeys,info) {
        console.log(checkedKeys)
        let checkArr = []
        if(this.checkStrictly){
          checkArr = checkedKeys.checked;
        }else{
          checkArr = checkedKeys
        }
        if(!this.multi){
          let arr = checkArr.filter(item => this.checkedKeys.indexOf(item) < 0)
          this.checkedKeys = [...arr]
          this.checkedRows = (this.checkedKeys.length === 0) ? [] : [info.node.dataRef]
        }else{
          this.checkedKeys = checkArr
          this.checkedRows = this.getCheckedRows(this.checkedKeys)
        }
          //---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------
        
        //---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------
      },
      getCheckStrictlyAllKeys(checkArr){
          let arr = new Set()
          checkArr.forEach(element => {
            arr.add(element)
          });
          return arr
      },
      onSelect(selectedKeys,info) {
        let keys = []
        keys.push(selectedKeys[0])
        if(!this.checkedKeys || this.checkedKeys.length===0 || !this.multi){
          this.checkedKeys = [...keys]
          this.checkedRows=[info.node.dataRef]
        }else{
          let currKey = info.node.dataRef.key
          if(this.checkedKeys.indexOf(currKey)>=0){
            this.checkedKeys = this.checkedKeys.filter(item=> item !==currKey)
          }else{
            this.checkedKeys.push(...keys)
          }
        }
        this.checkedRows = this.getCheckedRows(this.checkedKeys)
      },
      onExpand (expandedKeys) {
        this.expandedKeys = expandedKeys
        this.autoExpandParent = false
      },
      handleSubmit(){
        if(!this.checkedKeys || this.checkedKeys.length==0){
          if(this.needSelect){
            this.$message.warning('请选择数据!')
            return
          }
          this.$emit("ok",'')
        }else{
          let checkRow = this.getCheckedRows(this.checkedKeys)
          let keyStr = this.checkedKeys.join(",")
          this.$emit("ok", checkRow, keyStr)
        }
        this.handleClear()
      },
      handleCancel(){
        this.handleClear()
      },
      handleClear(){
        this.visible=false
        this.checkedKeys=[]
      },
      getParentKey(currKey,treeData){
        let parentKey
        for (let i = 0; i < treeData.length; i++) {
          const node = treeData[i]
          if (node.children && node.children.length>0) {
            if (node.children.some(item => item.key == currKey)) {
              parentKey = node.key
            }  if (this.getParentKey(currKey, node.children)) {
              parentKey = this.getParentKey(currKey, node.children)
            }
          }
        }
        return parentKey
      },
      getParentAllKey( pid ,parentKeys = []){

        let parentObj = this.dataList.find((item) => {
          
          return item.key == pid
        })
        if(!!parentObj  ){
          parentKeys.push(pid)
          pid = parentObj[this.parentConfig.parentKey]
          this.getParentAllKey(pid,parentKeys)
        }
      },
      onSearch(value){
        let expandedKeys =[]
        if(this.parentConfig.start){  
            this.dataList.map((item) => {
              if (item.title.indexOf(value) > -1) {
                return this.getParentAllKey(item[this.parentConfig.parentKey],expandedKeys)
              }
            })
        }else{
            expandedKeys = this.dataList.map((item) => {
              if (item.title.indexOf(value) > -1) {
                return this.getParentKey(item.key,this.treeData)
              }
              return null
          })
        }
        
        expandedKeys = expandedKeys.filter((item, i, self) => item && self.indexOf(item) === i)
      
        Object.assign(this, {
          expandedKeys,
          searchValue: value,
          autoExpandParent: true,
        })


      },
      // 根据 checkedKeys 获取 rows
      getCheckedRows(checkedKeys) {
        const forChildren = (list, key) => {
          for (let item of list) {
            if (item.key === key) {
              return item
            }
            if (item.children instanceof Array) {
              let value = forChildren(item.children, key)
              if (value != null) {
                return value
              }
            }
          }
          return null
        }

        let rows = []
        for (let key of checkedKeys) {
          let row = forChildren(this.treeData, key)
          if (row != null) {
            rows.push(row)
          }
        }
        return rows
      }
    }
  }

</script>

<style lang="less" scoped>
  // 限制部门选择树高度，避免部门太多时点击确定不便
  .my-dept-select-tree{
    height: 350px;
    overflow-y: scroll;
  }

</style>